import { Alert, Image, StyleSheet, Text, View } from "react-native"
import { pxDp } from "../../Utils/stylesKit";
import { Icon, Input, List, Toast, Button, } from '@ant-design/react-native'
import { useState } from "react";
import { loginApi,phoneCaptcha } from "../../Api/Login";
// 导入 useNavigation 钩子
import { useNavigation } from '@react-navigation/native';
import { saveSetItem } from "../../Utils/AsyncStorage";

const Login = () => {
    const navigation = useNavigation(); // 获取导航对象
    const [phoneNumber, setPhoneNumber] = useState('');
    const [phonePassword, setPhonePassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [isCaptchaLogin, setIsCaptchaLogin] = useState(false);
    const [captcha, setCaptcha] = useState(''); // 验证码状态
    const [captchaTimeShow, setCaptchaTimeShow] = useState(false); // 验证码时间显示隐藏
    const [captchaTime, setCaptchaTime] = useState(60); // 验证码倒计时


    const phoneChangeText = (text: string) => {
        Toast.removeAll()
        setPhoneNumber(text);
    }

    const validatePhoneNumber = () => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (isCaptchaLogin && phoneNumber && !phoneRegex.test(phoneNumber)) {
            Toast.show({
                content: '手机号格式不正确',
                position: 'top',
            })
        }
        return
    }
    // 切换登录方式
    const handleCaptchaLoginToggle = () => {
        setIsCaptchaLogin(!isCaptchaLogin); // 切换登录方式
        setPhonePassword(''); // 切换时清空密码
        setCaptcha(''); // 切换时清空验证码
    }

    const handleCaptchaTime = async () => {
        // 发送验证码逻辑
        const phoneRegex = /^1[3-9]\d{9}$/; // 手机号正则
        if (phoneNumber && phoneRegex.test(phoneNumber)) {
            setCaptchaTimeShow(true); // 显示倒计时
            const res = await phoneCaptcha({ phoneNumber });
            if (res.code === 0) {
                const timer = setInterval(() => {
                    setCaptchaTime(prevTime => {
                        if (prevTime === 0) {
                            clearInterval(timer); // 倒计时结束，清除定时器
                            setCaptchaTimeShow(false); // 隐藏倒计时
                            return 60; // 重置倒计时
                        }
                        return prevTime - 1; // 每秒减少1
                    });
                }, 1000)
                Toast.show({
                    content: '验证码已发送',
                    position: 'top',
                });
            }else{
                Toast.show({
                    content: '发送失败',
                    position: 'top',
                });
                setCaptchaTimeShow(false)
            }

        } else {
            Toast.show({
                content: '请输入正确的手机号',
                position: 'top',
            });
        }
    };
    // 登录逻辑
    const handleLogin = async() => {
      if(phoneNumber && phonePassword){
          const res:any = await loginApi( {userName:phoneNumber, password:phonePassword})
          if(res.code === 0){
              Toast.show({
                  content: '登录成功',
                  position: 'center',
                  duration: 1,
              });
             
              saveSetItem(res.data)
                // @ts-ignore
              navigation.navigate('Main');
          }else{
              Toast.show({
                  content: res.msg,
                  position: 'center',
              });
          }
      }
        
    }

    return (
        <View style={{ flex: 1, backgroundColor: '#fff' }}>
            <View style={{ paddingVertical: pxDp(44), paddingLeft: pxDp(50), paddingRight: pxDp(50) }}>
                <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                    <Text style={{ fontSize: pxDp(24), fontWeight: '500' }}>
                        {isCaptchaLogin ? '验证码登录' : '密码登录'}
                    </Text>
                </View>
                <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                    <Text style={{ fontSize: pxDp(14), color: '#ccc', marginTop: pxDp(10) }}>
                        未注册的手机号登录成功后将自动注册
                    </Text>
                </View>
                <View style={{ marginTop: pxDp(30) }}>
                    <Input
                        allowClear
                        prefix={
                            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                <Text style={{ marginRight: 4, fontSize: pxDp(20) }}>+86</Text>
                                <Icon style={{ marginTop: 2 }} name="caret-down" size={15} color="#333" />
                            </View>
                        }
                        style={{ borderBottomWidth: 0.4, borderBottomColor: '#E5E5E5' }}
                        placeholder="请输入手机号"
                        value={phoneNumber}
                        onChangeText={phoneChangeText}
                        onEndEditing={validatePhoneNumber}
                    />
                    {isCaptchaLogin ? (
                        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Input
                                allowClear
                                type="number"
                                maxLength={6}
                                style={{
                                    borderBottomWidth: 0.4,
                                    borderBottomColor: '#E5E5E5',
                                    flex: 1,
                                    marginTop: pxDp(20)
                                }}
                                placeholder="输入验证码"
                                value={captcha}
                                onChangeText={setCaptcha}
                                suffix={
                                    <View>
                                        {!captchaTimeShow ? (<Button
                                            size="small"
                                            style={{ height: 28, paddingVertical: 0, paddingHorizontal: 4, borderWidth: 0, backgroundColor: '#FF2442', }}
                                            onPress={handleCaptchaTime}
                                        >
                                            <Text style={{ fontSize: pxDp(14), color: '#fff' }}>验证码</Text>
                                        </Button>) : <Text style={{ fontSize: pxDp(14), color: '#ccc' }}>重新发送（{captchaTime}）</Text>}
                                    </View>
                                }
                            />

                        </View>
                    ) : (
                        <Input
                            allowClear
                            type={showPassword ? 'text' : 'password'}
                            style={{ borderBottomWidth: 0.4, borderBottomColor: '#E5E5E5', marginTop: pxDp(20) }}
                            placeholder="输入密码"
                            value={phonePassword}
                            onChangeText={setPhonePassword}
                            suffix={
                                <Icon
                                    color="#333"
                                    name={showPassword ? 'eye' : 'eye-invisible'}
                                    onPress={() => setShowPassword(!showPassword)}
                                />
                            }
                        />
                    )}
                </View>
                <View style={{ marginTop: pxDp(10), flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Icon name="swap" size={14} color="#666" />
                        <Text
                            style={{ fontSize: pxDp(14), color: '#666', marginLeft: 2 }}
                            onPress={handleCaptchaLoginToggle}
                        >
                            {isCaptchaLogin ? '密码登录' : '验证码登录'}
                        </Text>
                    </View>
                    {!isCaptchaLogin && (
                        <View>
                            <Text style={{ color: '#666' }}>忘记密码？</Text>
                        </View>
                    )}
                </View>
                <View style={{ paddingVertical: pxDp(20) }}>
                    {isCaptchaLogin ? (
                        <Button
                            size="large"
                            style={{ borderRadius: 30, backgroundColor: captcha ? '#FF2442' : '#F5F5F5', borderWidth: 0, height: 40 }}
                            disabled={!captcha}
                        >
                            <Text style={{ color: '#fff', fontSize: pxDp(20) }}>登录</Text>
                        </Button>
                    ) : (
                        <Button
                            size="large"
                            style={{ borderRadius: 30, backgroundColor: phonePassword ? '#FF2442' : '#F5F5F5', borderWidth: 0, height: 40 }}
                            disabled={!phonePassword}
                            onPress={handleLogin}
                        >
                            <Text style={{ color: '#fff', fontSize: pxDp(20) }}>登录</Text>
                        </Button>
                    )}
                </View>
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
})

export default Login;